package jehc.cloud.iot.live.common.worker;

import jehc.cloud.iot.live.model.CameraEntity;
import jehc.cloud.iot.live.common.service.LiveService;
import jehc.cloud.iot.live.common.util.ApplicationContextUtil;
import jehc.cloud.iot.live.common.util.CacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
 * @Desc 保活线程（保活器）
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Slf4j
public class KeepAliveWorker extends Thread {
    /**待处理队列*/
    public static Map<String, CameraEntity> keepAliveMap = new ConcurrentHashMap<String, CameraEntity>();

    public int errIndex=0;//错误计数

    public volatile int stopIndex=0;//安全停止线程标记

    /**
     *
     * @param cameraEntity
     */
    public static void put(CameraEntity cameraEntity){
        log.info("开始放入缓存..."+cameraEntity.getToken());
        keepAliveMap.put(cameraEntity.getToken(),cameraEntity);
        log.info("结束放入缓存..."+cameraEntity.getToken());
    }

    /**
     *
     */
    @Override
    public void run() {
        for(;errIndex==0;) {
            try {
                if(CollectionUtils.isEmpty(keepAliveMap)) {
                    continue;
                }
                Iterator iter = keepAliveMap.entrySet().iterator();
                while(iter.hasNext()) {
                    Map.Entry<String, CameraEntity> entry = (Map.Entry<String, CameraEntity>) iter.next();
                    CameraEntity cameraEntity = entry.getValue();
                    log.info("设备编号："+cameraEntity.getToken()+",ErrorCount："+cameraEntity.getErrorCount());
                    if(null != CacheUtil.STREAMMAP && null != CacheUtil.STREAMMAP.get(entry.getKey())){
                        //如果缓存中已经有了 说明该任务在其它地方已经加入执行了
                        log.info("该推流器在其它地方已加入了，ID号："+entry.getKey());
                        keepAliveMap.remove(entry.getKey());
                        continue;
                    }
                    if(cameraEntity.getErrorCount()>100){
                        //当错误大于100次则说明该设备无用了
                        log.info("终止连接，原因始终无法连接成功，该设备无效，ID号："+entry.getKey());
                        keepAliveMap.remove(entry.getKey());
                        continue;
                    }
                    //重启任务
                    log.info("保活线程已重启任务开始，ID号："+entry.getKey());
                    LiveService liveService = ApplicationContextUtil.getBean(LiveService.class);
                    liveService.live(cameraEntity);
                    keepAliveMap.remove(entry.getKey());//加入保活移除该元素
                    log.info("保活线程已重启任务完毕，ID号："+entry.getKey());
                    Thread.sleep(1000);
                }
            }catch (Exception e){
                e.printStackTrace();
                log.error("保活线程终止："+e.getMessage());
            }
        }
    }
//    /**
//     *
//     */
//    @Override
//    public void interrupt() {
//        stopIndex=1;
//    }

//    public static void main(String[]arg){
//        ConcurrentHashMap<String, String> map = new ConcurrentHashMap<String, String>();
//        map.put("A", "A");
//        map.put("B", "B");
//        map.put("C", "C");
//        map.put("A","C");
//        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
//        while (iterator.hasNext()) {
//            Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();
//            System.out.println( entry.getKey()+"----"+ entry.getValue());
//            map.remove("B");
//        }
//        System.out.println(map.toString());
//    }
}
